package com.boy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boy.entity.Permission;
import com.boy.entity.dto.PermissionDto;
import com.boy.mapper.PermissionMapper;
import com.boy.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author whd
 * @since 2024-05-23
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Permission getByPath(String path) {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("path", path);
        return permissionMapper.selectOne(wrapper);
    }

    @Override
    public List<PermissionDto> findAll() {
        List<Permission> permissions = permissionMapper.selectList(null);
        List<PermissionDto> permissionDtos = new ArrayList<>();
        permissions.forEach((it) ->
        {
            if (Objects.equals(it.getParentId(), "0")) {
                List<Permission> list = permissions.stream().filter(permission -> Objects.equals(permission.getParentId(), it.getId())).collect(Collectors.toList());
                PermissionDto permissionDto = new PermissionDto(it);
                permissionDto.setPermissions(list);
                permissionDtos.add(permissionDto);
            }
        });
        return permissionDtos;
    }
}
